package com.hj.deliveryorder.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.hj.common.core.domain.entity.SysUser;
import com.hj.common.exception.ServiceException;
import com.hj.common.utils.SecurityUtils;
import com.hj.common.utils.StringUtils;
import com.hj.common.utils.bean.BeanValidators;
import com.hj.deliveryorder.domain.DeliveryOrders;
import com.hj.deliveryorder.mapper.DeliveryOrdersMapper;
import com.hj.deliveryorder.service.IDeliveryOrdersService;
import com.hj.system.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Validator;


/**
 * 配送手机卡号的订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-07
 */
@Service
public class DeliveryOrdersServiceImpl implements IDeliveryOrdersService
{
    private static final Logger log = LoggerFactory.getLogger(DeliveryOrdersServiceImpl.class);
    @Autowired
    protected Validator validator;
    @Autowired
    private DeliveryOrdersMapper deliveryOrdersMapper;

    /**
     * 查询配送手机卡号的订单
     * 
     * @param id 配送手机卡号的订单主键
     * @return 配送手机卡号的订单
     */
    @Override
    public DeliveryOrders selectDeliveryOrdersById(Long id)
    {
        return deliveryOrdersMapper.selectDeliveryOrdersById(id);
    }

    @Override
    public Integer orderCount(DeliveryOrders deliveryOrders) {
        return deliveryOrdersMapper.orderCount(deliveryOrders);
    }

    /**
     * 查询配送手机卡号的订单列表
     * 
     * @param deliveryOrders 配送手机卡号的订单
     * @return 配送手机卡号的订单
     */
    @Override
    public List<DeliveryOrders> selectDeliveryOrdersList(DeliveryOrders deliveryOrders)
    {
        return deliveryOrdersMapper.selectDeliveryOrdersList(deliveryOrders);
    }

    /**
     * 新增配送手机卡号的订单
     * 
     * @param deliveryOrders 配送手机卡号的订单
     * @return 结果
     */
    @Override
    public int insertDeliveryOrders(DeliveryOrders deliveryOrders)
    {
        return deliveryOrdersMapper.insertDeliveryOrders(deliveryOrders);
    }

    /**
     * 修改配送手机卡号的订单
     * 
     * @param deliveryOrders 配送手机卡号的订单
     * @return 结果
     */
    @Override
    public int updateDeliveryOrders(DeliveryOrders deliveryOrders)
    {
        return deliveryOrdersMapper.updateDeliveryOrders(deliveryOrders);
    }

    /**
     * 批量删除配送手机卡号的订单
     * 
     * @param ids 需要删除的配送手机卡号的订单主键
     * @return 结果
     */
    @Override
    public int deleteDeliveryOrdersByIds(Long[] ids)
    {
        return deliveryOrdersMapper.deleteDeliveryOrdersByIds(ids);
    }

    /**
     * 删除配送手机卡号的订单信息
     * 
     * @param id 配送手机卡号的订单主键
     * @return 结果
     */
    @Override
    public int deleteDeliveryOrdersById(Long id)
    {
        return deliveryOrdersMapper.deleteDeliveryOrdersById(id);
    }

    @Override
    public String importOrder(List<DeliveryOrders> orderList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(orderList) || orderList.size() == 0)
        {
            throw new ServiceException("导入订单数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (DeliveryOrders order : orderList)
        {
            try
            {
                // 验证是否存在这个用户
                List<DeliveryOrders> oList = deliveryOrdersMapper.selectDeliveryOrdersList(order);
                if (StringUtils.isNull(oList) || oList.size() == 0)
                {
                    BeanValidators.validateWithException(validator, order);
                    order.setCreateBy(operName);
                    deliveryOrdersMapper.insertDeliveryOrders(order);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、电话 " + order.getPhone() + " 导入成功");
                }
                else if (updateSupport)
                {
                    BeanValidators.validateWithException(validator, order);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、电话 " + order.getPhone() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、电话 " + order.getPhone() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、电话 " + order.getPhone() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public int assignOrders(DeliveryOrders deliveryOrders,SysUser user) {
        if(StringUtils.isNull(deliveryOrders)||StringUtils.isNull(deliveryOrders.getOrderIds())){
            throw new ServiceException("分配订单id列表不能为空！");
        }
        String orderIdsStr = deliveryOrders.getOrderIds();
        if (orderIdsStr == null || orderIdsStr.isEmpty()) {
            return 0;
        }
        // 字符串转 Long 列表（避免使用实体类，直接存储 ID）
        List<Long> orderIds = Arrays.stream(orderIdsStr.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .map(Long::parseLong)
                .collect(Collectors.toList());
        int count = 0;
        if (!orderIds.isEmpty()) {
            // 直接传入 Long 列表
            count = deliveryOrdersMapper.assignOrders(orderIds,String.valueOf(user.getUserId()),user.getUserName());
        }
        return count;
    }

}
